import { message } from 'ant-design-vue';
import axios from 'axios'
import { store } from '@/store' 
import i18n from '@/locales/index' 
const { t } = i18n.global
import { clearSpecifiedLocalStorage, getToken, filterNull , getBaseUrl, getLocalStorage, getLang } from '@/utils'

const url = getBaseUrl(process.env.NODE_ENV)
const customAxios = axios.create({
  baseURL: url
})

const initStore = () => {
  store.commit('updateState', {
    tabs: [],
    activeFirstMenu: null,
    activeFirstMenuName: null,
    subMenu: [],
    activeSideMenu: '',
  })
}
const CancelToken = axios.CancelToken
const cancels = []

customAxios.interceptors.request.use(
  async function (request) {
    // 更新token
    if (request.headers) {
      request.headers.Authorization = getToken()
      request.headers.currentLineNo = getLocalStorage('currentLine') ? getLocalStorage('currentLine').lineNo : null
      request.headers['content-language'] = getLang()
    }

    return request
  },
  function (error) {
    return Promise.reject(error)
  }
)

// 响应拦截 处理token是否过期
customAxios.interceptors.response.use(
  (response) => {
    const { data } = response
    const { code } = data
    // const { expire } = getCurrentUser()
    const flag =  Date.now() < 1000
    const noTokenList = ['/login']
    const pathFlag = !noTokenList.includes(location.pathname)

    if (pathFlag && (flag || code === 40101 || code === 401)) {
      
      // const retryOriginalRequest = new Promise((resolve) => {
      //   addSubscriber(() => {
      //     resolve(customAxios(config))
      //   })
      // })
      // return retryOriginalRequest
    }
    if (location.pathname !== '/login' && code === 40101) {
      message.warning(t('other.loginExpired'))
      // token失效
      clearSpecifiedLocalStorage()
      location.replace('/login')
      initStore()
    }
    return response.data
  },
  (error) => {
  console.log("🚀 ~ file: request.js ~ line 53 ~ error", error)
    const {  code } = error
    if (
      location.pathname !== '/login' && code === 40101 ) {
        message.warning(t('other.loginExpired'))
        clearSpecifiedLocalStorage()
      location.replace('/login')
      initStore()
      // token失效
    }
    return Promise.reject(error)
  }
)

const apiAxios = async ( method, url, params, success, failure) => {
  params = filterNull(params)
  // const noTokenList = []
  const outFlag = method === 'export'
  const instanceParams= {
    method: outFlag? 'POST' :method,
    url: url,
    data:['POST','PUT','DELETE', 'export'].includes(method) ? params : null,
    params: method === 'GET' ? params : null,
    // baseURL: root,
    withCredentials: true,
    headers: {
      common: {
        Authorization: getToken(),
      }
    },
    cancelToken: new CancelToken(function executor(c) {
      // executor 函数接收一个 cancel 函数作为参数
      cancels.push(c)
    })
  }
  if (outFlag)   instanceParams.responseType = 'blob' 
  // const flag = noTokenList.some((i) => url.includes(i))
  // if (flag) {
  //   // 不需要携带token的接口  去除 token
  //   // delete instanceParams.headers.common.authorization
  //   // delete instanceParams.headers.common.refresh_token
  // }
  try {
    const responseData = await customAxios(instanceParams)
    // 接口状态码处理
    if (outFlag) {
      success && success()
      return responseData
    }
    if (responseData.code == 200) {
      success && success()
      return responseData
    } else {
      failure && failure()
      responseData.code !== 40101 &&
        responseData.msg &&
        message.error(responseData.msg || t('common.doError'))
      if(responseData.code === 40101) {
        message.warning('登录过期,请重新登录！')
        clearSpecifiedLocalStorage()
        location.replace('/login')
        initStore()
      }
      return Promise.reject(responseData)
    }
  } catch (error) {
    failure && failure()
    // console.log('!!!!!!!!', error);
    message.error(error.response.data.msg || t('components.getDataErrorPleaseHolder'))
  }
}

export default {
  getAction: function ( url, params, success, failure ) {
    return apiAxios('GET', url, params, success, failure)
  },
  postAction: function (url, params, success, failure) {
    return apiAxios('POST', url, params, success, failure)
  },
  putAction: function (url, params, success, failure) {
    return apiAxios('PUT', url, params, success, failure)
  },
  deleteAction: function (url, params, success, failure) {
    return apiAxios('DELETE', url, params, success, failure)
  },
  downFile: function ( url, params, success, failure ) {
    return apiAxios('export', url, params, success, failure)
  },
  cancels // 切换路由之前 遍历cancels 执行方法 取消之前的请求
}
